package org.mspring.platform.web.freemarker;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.ClassUtils;
import org.mspring.platform.utils.PropertiesUtils;
import org.mspring.platform.web.freemarker.directive.AbstractDirectiveModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import freemarker.template.Configuration;
import freemarker.template.TemplateException;

/**
 *
 * @author Gao Youbo
 * @since 2012-7-26
 */
public class ExtendsFreeMarkerConfigurer extends FreeMarkerConfigurer {

    private static final Logger log = LoggerFactory.getLogger(ExtendsFreeMarkerConfigurer.class);

    @Override
    public Configuration createConfiguration() throws IOException, TemplateException {
        Map<String, Object> variables = addVariables();
        setFreemarkerVariables(variables);
        return super.createConfiguration();
    }

    /**
     * 获取variables.properties中配置的variable
     *
     * @return
     */
    @SuppressWarnings("rawtypes")
    private Map<String, Object> addVariables() {
        Map<String, Object> variables = new HashMap<>();
        Map<String, String> map = PropertiesUtils.getPropertyMap("variables.properties");
        for (Map.Entry<String, String> entry : map.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
            if (org.apache.commons.lang3.StringUtils.isNotBlank(key)) {
                try {
                    Class clazz = ClassUtils.getClass(value);
                    if (AbstractDirectiveModel.class.isAssignableFrom(clazz)) {
                        AbstractDirectiveModel model = (AbstractDirectiveModel) clazz.newInstance();
                        variables.put(key, model);
                    } else {
                        variables.put(key, value);
                    }
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException e) {
                    log.error("can't found AbstractDirectiveModel named [" + value + "], set string variable.");
                    variables.put(key, value);
                }
            }
        }
        return variables;
    }
}
